package com.me.regex;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class AnalyseTime {
		
	final static String DATE_PATTERN1 = "\\b([0-9]{4})[\\/-](0?[1-9]|1[0-2])[\\/-](0?[1-9]|[12][0-9]|3[01])\\b";	//yyyy MM dd
	final static String DATE_PATTERN2 = "\\b(0?[1-9]|[12][0-9]|3[01])[\\/-](0?[1-9]|1[0-2])[\\/-]([0-9]{4})\\b";	//dd MM yyyy
	final static String DATE_PATTERN3 = "\\b(0?[1-9]|1[0-2])[\\/-](0?[1-9]|[12][0-9]|3[01])[\\/-]([0-9]{4})\\b";	//MM dd yyyy

	
	public static ArrayList<Date> analyse(String input) {
		
		ArrayList<Date> output = new ArrayList<Date>();
				
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			
		//match pattern 1
		Pattern datePattern = Pattern.compile(DATE_PATTERN1);
		Matcher matcher = datePattern.matcher(input);
		while (matcher.find()) {
			try {
				output.add(formatter.parse(matcher.group()));
				input = input.replaceAll(DATE_PATTERN1, "");
			} catch (ParseException e) {}
			
			if (input.length() < 2 || output.size() == 2) return output;
		}
				
		//match pattern 2
		datePattern = Pattern.compile(DATE_PATTERN2);
		matcher = datePattern.matcher(input);
		while (matcher.find()) {
			try {
				output.add(formatter.parse(matcher.group(3)+"-"+matcher.group(2)+"-"+matcher.group(1)));
				input = input.replaceAll(DATE_PATTERN2, "");
			} catch (ParseException e) {}
			
			if (input.length() < 2 || output.size() == 2) return output;
		}
		
		if (input.length() < 2 || output.size() > 2) return output;

		//match pattern 3
		datePattern = Pattern.compile(DATE_PATTERN3);
		matcher = datePattern.matcher(input);
		while (matcher.find()) {
			try {
				output.add(formatter.parse(Calendar.getInstance().get(Calendar.YEAR)+"-"+matcher.group(2)+"-"+matcher.group(1)));
				input = input.replaceAll(DATE_PATTERN3, "");
			} catch (ParseException e) {}
			
			if (input.length() < 2 || output.size() == 2) return output;
		}
		
		//match pattern 4
		datePattern = Pattern.compile(DATE_PATTERN4);
		matcher = datePattern.matcher(input);
		while (matcher.find()) {
			try {
				output.add(formatter.parse(Calendar.getInstance().get(Calendar.YEAR)+"-"+matcher.group(1)+"-"+matcher.group(2)));
				input = input.replaceAll(DATE_PATTERN4, "");
			} catch (ParseException e) {}
			
			if (input.length() < 2 || output.size() == 2) return output;

		}
		
		return output;
	}

}
